package com.weilai.controller;

import com.github.pagehelper.PageInfo;
import com.weilai.controller.exceptionHandler.BusinessException;
import com.weilai.controller.exceptionHandler.Code;
import com.weilai.controller.exceptionHandler.SystemException;
import com.weilai.domain.*;
import com.weilai.service.*;
import com.weilai.util.UploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import springfox.documentation.swagger.readers.operation.SwaggerOperationModelsProvider;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;

@Controller
@Api(tags = "视频",description = "对视频进行相关操作的接口")
public class VideosController {
    @Autowired
    private VideosService videosService;
    @Autowired
    private UserService userService;
    @Autowired
    private PostsService postsService;
    @Autowired
    private FollowersService followersService;
    @Autowired
    private ThoughtService thoughtService;
    @Autowired
    private CommentsService commentsService;
    @Autowired
    private SwaggerOperationModelsProvider swaggerOperationModelsProvider;

    // 添加视频标题和简介
    @ApiOperation(value = "添加视频标题和简介的方法")
    @PostMapping("/videosDescription/add")
    public ModelAndView addVideoDescription(@RequestParam String title,
                            @RequestParam String description,
                            @RequestParam String videoUrl,
                            @RequestParam String tagName,
                            HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        try {
            // 参数校验
            if (title == null || title.trim().isEmpty()) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "视频标题不能为空");
            }
            if (description == null || description.trim().isEmpty()) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "视频描述不能为空");
            }
            if (videoUrl == null || videoUrl.trim().isEmpty()) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "视频链接不能为空");
            }
//            if (file == null || file.isEmpty()) {
//                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "请选择要上传的视频文件");
//            }

//            // 文件大小校验 (10MB)
//            long maxSize = 10 * 1024 * 1024;
//            if (file.getSize() > maxSize) {
//                throw new BusinessException(Code.PROJECT_RESOURCE_LIMIT, "视频文件大小不能超过10MB");
//            }

            Videos videos = new Videos();
            videos.setTitle(title);
            videos.setDescription(description);
            // 修正：根据标签名称查询标签ID，并增加存在性校验
            Tag tag = videosService.getTagByTagName(tagName);
            if (tag == null) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "标签不存在：" + tagName);
            }
            videos.setTagId(tag.getId());
            int userId = (int) request.getSession().getAttribute("userId");
            videos.setUserId(userId);

            videos.setFilePath(videoUrl);

            videosService.addVideoDescription(videos);
            mav.addObject("result", "视频标题和简介添加成功");
            mav.addObject("videoUrl","");
            mav.setViewName("postVideo");
            return mav;
        } catch (BusinessException e) {
            throw e;
        }
//        catch (IOException e) {
//            throw new SystemException(Code.SYSTEM_IO_ERROR, "视频文件上传失败", e);
//        }
        catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "添加视频标题和简介时数据库错误", e);
        }
    }
    //添加视频的方法
    @ApiOperation(value = "添加视频的方法")
    @PostMapping("/videos/add")
    public ModelAndView addVideoFile(
            @RequestParam("file") MultipartFile file,// 明确指定参数名
            HttpServletRequest request,RedirectAttributes redirectAttributes) throws IOException {  // 添加request参数

        ModelAndView mav = new ModelAndView();
        try {
            // 1. 文件基础校验
            if (file == null || file.isEmpty()) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "请选择要上传的视频文件");
            }

            // 2. 文件类型校验（新增关键校验）
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("video/")) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "仅支持视频文件格式");
            }

            // 3. 文件大小校验 (5G)
            long maxSize = 5L * 1024 * 1024 * 1024;
            if (file.getSize() > maxSize) {
                throw new BusinessException(Code.PROJECT_RESOURCE_LIMIT, "视频文件大小不能超过5G");
            }

            // 4. 上传处理
            Videos videos = new Videos();
            String fileName = UploadUtil.upload(file);
            videos.setFilePath(fileName);

            // 5. 获取当前用户（示例）
            Integer userId = (Integer) request.getSession().getAttribute("userId");
            videos.setUserId(userId);

//            videosService.addVideoFile(videos);

//            mav.addObject("result", "视频添加成功");
//            mav.addObject("videoUrl", fileName);  // 返回视频URL
            redirectAttributes.addFlashAttribute("result","添加视频成功");
            redirectAttributes.addFlashAttribute("videoUrl",fileName);
            mav.setViewName("redirect:/postVideo");
            return mav;

        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "添加视频失败", e);
        }
    }


    // 删除视频
    @ApiOperation(value = "删除视频的方法")
    @PostMapping("/videos/delete")
    @ResponseBody
    public Map<String, Object> deleteById(@RequestParam int id, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        try {
            int userId = (int) request.getSession().getAttribute("userId");
            Videos video = videosService.selectById(id);

            if (video == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "视频不存在或已被删除");
            }
            if (video.getUserId() != userId) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "无权删除他人视频");
            }

            videosService.deleteById(id);
            result.put("message", "删除成功");
            result.put("page","/personCenterVideo");
        } catch (BusinessException e) {
            result.put("message", e.getMessage());
        } catch (Exception e) {
            result.put("message", "删除视频失败");
        }
        return result;
    }

    // 回显数据以便修改视频
    @ApiOperation(value = "回显数据的方法")
    @GetMapping("/updateVideos")
    public ModelAndView updateVideos(@RequestParam int id) {
        try {
            Videos videos = videosService.selectById(id);
            if (videos == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "未找到该视频");
            }

            ModelAndView mav = new ModelAndView();
            mav.addObject("videos", videos);
            mav.setViewName("updatePage");
            return mav;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "查询视频信息时数据库错误", e);
        }
    }

    // 修改视频
    @ApiOperation(value = "修改视频的方法")
    @PostMapping("/videoUpdate")
    public ModelAndView update(@RequestParam int id,
                               @RequestParam String title,
                               @RequestParam String description,
                               @RequestParam MultipartFile file,
                               HttpServletRequest request) {
        try {
            // 参数校验
            if (title == null || title.trim().isEmpty()) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "视频标题不能为空");
            }
            if (description == null || description.trim().isEmpty()) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "视频描述不能为空");
            }

            int userId = (int) request.getSession().getAttribute("userId");
            Videos existingVideo = videosService.selectById(id);

            if (existingVideo == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "未找到该视频");
            }
            if (existingVideo.getUserId() != userId) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "无权修改他人视频");
            }

            Videos videos = new Videos();
            videos.setVideoId(id);
            videos.setTitle(title);
            videos.setDescription(description);

            if (file != null && !file.isEmpty()) {
                // 文件大小校验 (10MB)
                long maxSize = 10 * 1024 * 1024;
                if (file.getSize() > maxSize) {
                    throw new BusinessException(Code.PROJECT_RESOURCE_LIMIT, "视频文件大小不能超过10MB");
                }
                String fileName = UploadUtil.upload(file);
                videos.setFilePath(fileName);
            } else {
                videos.setFilePath(existingVideo.getFilePath());
            }

            videosService.update(videos);
            ModelAndView mav = new ModelAndView();
            mav.addObject("result", "视频更新成功");
            mav.setViewName("userMainPage");
            return mav;
        } catch (BusinessException e) {
            throw e;
        } catch (IOException e) {
            throw new SystemException(Code.SYSTEM_IO_ERROR, "视频文件上传失败", e);
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "修改视频时数据库错误", e);
        }
    }
    // 在首页查询所有视频
//    @ApiOperation(value = "在首页查询所有视频的方法")
//    @GetMapping("/mainPageVedio")
//    public ModelAndView selectAllVideos(HttpServletRequest request) {
//        try {
//            List<Videos> videos = videosService.selectAllVideos();
//            User u = (User) request.getSession().getAttribute("user");
//
//            ModelAndView mav = new ModelAndView();
//            if (videos == null || videos.isEmpty()) {
//                mav.addObject("message", "暂无视频内容");
//            } else {
//                List<User> users = new ArrayList<>();
//                for (Videos video : videos) {
//                    User user = userService.getUserById(video.getUserId());
//                    users.add(user);
//                }
//                mav.addObject("users", users);
//                mav.addObject("videos", videos);
//            }
//            mav.addObject("user", u);
//            mav.setViewName("mainPageVedio");
//            return mav;
//        } catch (Exception e) {
//            throw new SystemException(Code.SYSTEM_DB_ERROR, "查询所有视频时数据库错误", e);
//        }
//    }
    @ApiOperation(value ="首页初始视频加载（前10条）")
    @GetMapping("/mainPageVedio")
    public ModelAndView loadInitialVideos(HttpServletRequest request,
                                      @RequestParam(defaultValue = "1") int pageNum,
                                      @RequestParam(defaultValue = "15") int pageSize) {
        try {
            //获取视频分页数据
            PageInfo<Videos> pageInfo = videosService.selectAllVideos(pageNum, pageSize);
            if (pageInfo.getList().isEmpty() || pageInfo == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "暂无数据");
            }
            //获取视频对应用户的信息
            List<User> users = new ArrayList<>();
            for (Videos video : pageInfo.getList()) {
                User user = userService.getUserById(video.getUserId());
                users.add(user);
            }
            // 判断用户角色，决定返回的视图
            User user = (User) request.getSession().getAttribute("user");
            String viewName = "mainPageVedio";
            if (user != null && "admin".equals(user.getRole())) {
                viewName="mainPageVideoManager";

            }
            // 遍历视频列表，判断每个帖子用户是否点赞
            if (user!= null) {
                for (Videos video : pageInfo.getList()) {
                    int isLike = videosService.isLiked(video.getVideoId(), user.getId());
                    video.setIsLike(isLike);
                }
            }
            return new ModelAndView(viewName)
                    .addObject("pageInfo", pageInfo)
                    .addObject("users", users);
        } catch (BusinessException e) {
            throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND,"业务异常");
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "查询列表失败",e);
        }
    }
    @ApiOperation(value = "分页加载更多视频")
    @GetMapping("/mainPageVedio/more")
    public ResponseEntity<Map<String, Object>> loadMoreVideos(
            HttpServletRequest request,
            @RequestParam(defaultValue = "2") int pageNum,
            @RequestParam(defaultValue = "15") int pageSize
    ) {

        try {
            //获取视频分页数据
            PageInfo<Videos> pageInfo = videosService.selectAllVideos(pageNum, pageSize);
            if (pageInfo.getList().isEmpty() || pageInfo == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "暂无数据");
            }

            // 获取视频对应的用户信息，添加空值检查
            List<User> users = new ArrayList<>();
            for (Videos video : pageInfo.getList()) {
                User user = userService.getUserById(video.getUserId());
                if (user != null) {
                    users.add(user);
                } else {
                    return ResponseEntity.ok(Collections.singletonMap("message", "未查询到用户"));
                }
            }

            // 判断用户角色
            User user = (User) request.getSession().getAttribute("user");
            // 遍历视频列表，判断每个帖子用户是否点赞
            if (user!= null) {
                for (Videos video : pageInfo.getList()) {
                    int isLike = videosService.isLiked(video.getVideoId(), user.getId());
                    video.setIsLike(isLike);
                }
            }

            // 构建返回数据
            Map<String, Object> response = new HashMap<>();
            response.put("pageInfo", pageInfo);
            response.put("users", users);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            // 记录日志
            e.printStackTrace();
            // 根据业务异常返回合适的HTTP状态码，比如400表示请求有误
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Collections.singletonMap("error", e.getMessage()));
        } catch (Exception e) {
            // 记录日志
            e.printStackTrace();
            // 对于其他异常返回500表示服务器内部错误
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Collections.singletonMap("error", "查询列表失败"));
        }
    }

    // 查询别人所有视频
    @ApiOperation(value = "查询别人所有视频的方法")
    @GetMapping("/videos/selectAllUsersVideos")
    public ModelAndView selectAllUsersVideos(@RequestParam int userId) {
        try {
            List<Videos> videos = videosService.selectAllUsersVideos(userId);
            if (videos == null || videos.isEmpty()) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "该用户暂无视频内容");
            }

            List<User> users = new ArrayList<>();
            for (Videos video : videos) {
                User user = userService.getUserById(video.getUserId());
                if (user == null) {
                    throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "用户信息不存在");
                }
                users.add(user);
            }

            ModelAndView mav = new ModelAndView();
            mav.addObject("user", users);
            mav.addObject("Videos", videos);
            mav.setViewName("allUsersVideos");
            return mav;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "查询用户视频时数据库错误", e);
        }
    }

    // 查询自己所有视频
    @ApiOperation(value = "查询自己所有视频的方法")
    @GetMapping("/videos/selectMyAllVideos")
    public ModelAndView selectMyAllVideos(HttpServletRequest request) {
        try {
            int userId = (int) request.getSession().getAttribute("userId");
            List<Videos> videos = videosService.selectMyAllVideos(userId);

            ModelAndView mav = new ModelAndView();
            if (videos == null || videos.isEmpty()) {
                mav.addObject("message", "您还没有发布过视频");
            } else {
                List<User> users = new ArrayList<>();
                for (Videos video : videos) {
                    User user = userService.getUserById(video.getUserId());
                    users.add(user);
                }
                mav.addObject("user", users);
                mav.addObject("Videos", videos);
            }
            mav.setViewName("personCenterVideo");
            return mav;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "查询个人视频时数据库错误", e);
        }
    }

    // 根据标题关键字查询视频
    @ApiOperation(value = "根据标题关键字查询视频的方法")
    @GetMapping("/videos/select/title")
    public ModelAndView selectByTitle(@RequestParam String title) {
        try {
            if (title == null || title.trim().isEmpty()) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "搜索关键词不能为空");
            }

            List<Videos> videos = videosService.selectByTitle(title);
            ModelAndView mav = new ModelAndView();

            if (videos == null || videos.isEmpty()) {
                mav.addObject("message", "未找到相关视频");
            } else {
                List<User> users = new ArrayList<>();
                for (Videos video : videos) {
                    User user = userService.getUserById(video.getUserId());
                    users.add(user);
                }
                mav.addObject("user", users);
                mav.addObject("Videos", videos);
            }
            mav.setViewName("titlePosts");
            return mav;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "按标题搜索视频时数据库错误", e);
        }
    }

    // 根据时间范围查询视频
    @ApiOperation(value = "根据时间范围查询视频的方法")
    @GetMapping("/videos/select/date")
    public ModelAndView selectByDate(@RequestParam String date1, @RequestParam String date2) {
        try {
            // 日期格式校验
            String format = "yyyy-MM-dd";
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format);
            LocalDate.parse(date1, dtf);
            LocalDate.parse(date2, dtf);

            List<Videos> videos = videosService.selectByDate(date1, date2);
            ModelAndView mav = new ModelAndView();

            if (videos == null || videos.isEmpty()) {
                mav.addObject("message", "该时间段内没有视频");
            } else {
                List<User> users = new ArrayList<>();
                for (Videos video : videos) {
                    User user = userService.getUserById(video.getUserId());
                    users.add(user);
                }
                mav.addObject("user", users);
                mav.addObject("videos", videos);
            }
            mav.setViewName("datePosts");
            return mav;
        } catch (DateTimeParseException e) {
            throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "日期格式错误，请按照yyyy-MM-dd的格式输入");
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "按时间范围查询视频时数据库错误", e);
        }
    }

    //根据id查询视频
    @ApiOperation(value="根据id查询视频的方法")
    @GetMapping("/videos/select/id")
    public ModelAndView selectById(@RequestParam int id, HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();

        // 参数校验
        if (id <= 0) {
            throw new BusinessException(
                    Code.PROJECT_VALIDATE_ERROR,
                    "视频ID必须为正整数"
            );
        }

        try {
            // 查询视频
            Videos videos = videosService.selectById(id);
            if (videos == null) {
                throw new BusinessException(
                        Code.PROJECT_DATA_NOT_FOUND,
                        "视频不存在"
                );
            }

            // 查询用户信息
            User user = userService.getUserById(videos.getUserId());

            if (user == null) {
                throw new BusinessException(
                        Code.PROJECT_DATA_NOT_FOUND,
                        "用户不存在"
                );
            }
            user.setEmail("***");
            user.setPassword("***");
            // 查询用户相关数据
            List<Posts> p = postsService.selectByUserId(videos.getUserId());
            List<Thought> t = thoughtService.selectAllUsersThought(videos.getUserId());
            List<User> f = followersService.selectFansById(videos.getUserId());

            User user1 =(User) request.getSession().getAttribute("user");
            boolean isFollowing = false;
            boolean isLiked = false;
            if(user1 != null) {
                //判断是否点赞
                isLiked = videosService.isLikedByUser(user1.getId(),id);
                //判断是否关注
                isFollowing = followersService.isFollowing(user1.getId(), videos.getUserId());
            }

            // 设置视图数据

            mav.addObject("user", user);
            mav.addObject("videos", videos);
            mav.addObject("postsNum", p != null ? p.size() : 0);
            mav.addObject("thoughtNum", t != null ? t.size() : 0);
            mav.addObject("fansNum", f != null ? f.size() : 0);
            mav.addObject("isFollowing",isFollowing);//添加关注状态到视图
            mav.addObject("isLiked",isLiked);
            mav.setViewName("videoDetail");

        } catch (BusinessException e) {
            // 业务异常直接抛出
            throw e;
        } catch (Exception e) {
            // 系统异常包装后抛出
            throw new SystemException(
                    Code.SYSTEM_DB_ERROR,
                    "查询帖子详情失败",
                    e
            );
        }

        return mav;
    }

    // 点赞
    @ApiOperation(value = "点赞的方法")
    @PostMapping("/videos/like")
    @ResponseBody
    public Map<String,Object> like(@RequestParam int videoId, HttpServletRequest request) {
        try {
            int userId = (int) request.getSession().getAttribute("userId");
            Videos video = videosService.selectById(videoId);

            if (video == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "视频不存在");
            }
//            if (video.getUserId() == userId) {
//                throw new BusinessException(Code.PROJECT_OPERATION_CONFLICT, "不能给自己的视频点赞");
//            }
            return videosService.like(userId, videoId);
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "点赞操作时数据库错误", e);
        }
    }

    // 获取指定视频的评论并展示
    @ApiOperation(value = "获取指定视频所有评论的方法")
    @GetMapping("/videosComments")
    public ResponseEntity<?> getVideosComments(
            @RequestParam int videoId,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "5") int pageSize,
            HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 校验视频是否存在
            Videos videos = videosService.selectById(videoId);
            if (videos == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "视频不存在");
            }

            // 获取分页评论数据
            PageInfo<Comments> commentsPageInfo = commentsService.getCommentsByVideoIdWithPaging(videoId, pageNum, pageSize);
            List<Comments> comments = commentsPageInfo.getList();

            // 处理无评论情况
            if (pageNum == 1 && (comments == null || comments.isEmpty())) {
                response.put("info","暂无评论");
            }

            // 逐个获取评论用户信息（也有批量方式，效率高速度快难度大）
            List<User> commentUsers = new ArrayList<>();
            for (Comments comment : comments) {
                User user = userService.getUserById(comment.getUserId());
                if (user == null) {
                    throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "用户信息缺失");
                }
                commentUsers.add(user);
            }


            // 获取视频作者信息
            User videoAuthor = userService.getUserById(videos.getUserId());
            videoAuthor.setEmail("***");
            videoAuthor.setPassword("***");
            // 处理用户点赞状态
            Integer userId = (Integer) request.getSession().getAttribute("userId");
            if (userId != null) {
                for (Comments comment : comments) {
                    int isLiked = commentsService.isLikedByUser(userId, comment.getId());
                    comment.setIsLiked(isLiked);
                }
            }

            // 构建响应数据

            response.put("userId", userId);
            response.put("videos", videos);
            response.put("comments", comments);
            response.put("commentsCount", commentsPageInfo.getTotal());
            response.put("videoAuthor", videoAuthor);
            response.put("commentUsers", commentUsers);
            response.put("pageNum", pageNum);
            response.put("pageSize", pageSize);
            response.put("totalPages", commentsPageInfo.getPages());
            response.put("hasNextPage", commentsPageInfo.isHasNextPage());

            return  ResponseEntity.ok(response);

        } catch (BusinessException e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", e.getErrorCode());
            error.put("errorInfo", e.getErrorMessage());
            return new  ResponseEntity<>(error, HttpStatus.NOT_FOUND);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> error = new HashMap<>();
            error.put("code", Code.SYSTEM_DB_ERROR);
            error.put("errorInfo", "获取评论失败");
            return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 评论
    @ApiOperation(value = "评论的方法")
    @PostMapping("/videos/comment")
    @ResponseBody // 添加该注解,表示Spring应返回JSON数据
    public ResponseEntity<Map<String, Object>> comment(
            @RequestParam String content,
            @RequestParam int videoId,
            HttpServletRequest request) {

        Map<String, Object> response = new HashMap<>();
        try {
            // 参数校验
            if (content == null || content.trim().isEmpty()) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "评论内容不能为空");
            }

            // 权限校验
            User user = (User) request.getSession().getAttribute("user");
            if (user == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "用户未登录");
            }

            // 视频校验
            Videos videos = videosService.selectById(videoId);
            if (videos == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "视频不存在");
            }

            // 创建评论
            Comments comments = new Comments();
            comments.setContent(content);
            comments.setUserId(user.getId());
            comments.setVideoId(videoId);
            //添加评论信息
            String result = videosService.comment(comments);


            //获取该视频所有评论
            List<Comments> commentList = videosService.getCommentsByVideoId(videoId);
            //获取所有视频的用户
            List<User> userList = new ArrayList<>();
            for(Comments comments1 : commentList){
                User userById = userService.getUserById(comments1.getUserId());
                user.setEmail("***");
                user.setPassword("***");
                userList.add(userById);
            }

            // 构建成功响应
            response.put("success", true);
            response.put("data", result);
            response.put("commentList", commentList);
            response.put("user", user);
            response.put("userList", userList);
            return ResponseEntity.ok(response);

        } catch (BusinessException e) {
            // 业务异常处理
            response.put("success", false);
            response.put("errorCode", e.getErrorCode());
            response.put("errorMessage", e.getErrorMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        } catch (Exception e) {
            // 系统异常处理
            e.printStackTrace();
            response.put("success", false);
            response.put("errorCode", Code.SYSTEM_DB_ERROR);
            response.put("errorMessage", "发表评论失败");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    // 浏览
    @ApiOperation(value = "浏览的方法")
    @PostMapping("/videos/view")
    public ModelAndView view(@RequestParam int videoId) {
        try {
            Videos video = videosService.selectById(videoId);
            if (video == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "视频不存在");
            }

            videosService.view(videoId);
            ModelAndView mav = new ModelAndView();
            mav.addObject("result", "浏览成功");
            return mav;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "记录浏览时数据库错误", e);
        }
    }

    // 转发
    @ApiOperation(value = "转发的方法")
    @PostMapping("/videos/share")
    public ModelAndView share(@RequestParam int videoId) {
        try {
            Videos video = videosService.selectById(videoId);
            if (video == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "视频不存在");
            }

            videosService.share(videoId);
            ModelAndView mav = new ModelAndView();
            mav.addObject("result", "转发成功");
            return mav;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "记录转发时数据库错误", e);
        }
    }

    // 取消点赞
    @ApiOperation(value = "取消点赞的方法")
    @PostMapping("/videos/cancelLike")
    @ResponseBody
    public Map<String,Object> cancelLike(@RequestParam int videoId, HttpServletRequest request) {
        try {
            int userId = (int) request.getSession().getAttribute("userId");
            Videos video = videosService.selectById(videoId);

            if (video == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "视频不存在");
            }
            return videosService.cancelLike(userId, videoId);
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "取消点赞时数据库错误", e);
        }
    }

    @ApiOperation(value = "删除的评论的方法")
    @ResponseBody
    @PostMapping("/videos/comment/user")
    public Map<String, Object> deleteCommentByUser(@RequestParam int commentId, HttpServletRequest request) {
        try {
            // 权限校验
            Object userIdObj = request.getSession().getAttribute("userId");
            if (userIdObj == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "用户未登录，请先登录");
            }
            int userId = (int) userIdObj;

            // 检查评论是否存在且属于当前用户
            Comments comment = videosService.getCommentById(commentId);
            int videoId=comment.getVideoId();
            if (comment == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "评论不存在或已被删除");
            }
            // 检查当前用户是否是视频作者
            Videos videos = videosService.selectById(comment.getVideoId());
            if (comment.getUserId() == userId||videos.getUserId() == userId) {
                // 执行删除操作
                String result = videosService.deleteCommentByUser(commentId, userId);

                // 查询删除后的评论列表
                List<Comments> commentsList = videosService.getCommentsByVideoId(videoId);

                // 构建返回的JSON数据
                Map<String, Object> response = new HashMap<>();
                response.put("result", result);
                response.put("commentsList", commentsList);

                return response;
            }
            else{
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "无权删除他人评论");
            }
        } catch (BusinessException e) {
            throw e; // 业务异常直接抛出
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "删除评论操作失败", e);
        }
    }

//    // 作者删除评论
//    @ApiOperation(value = "作者删除评论的方法")
//    @PostMapping("/videos/comment/author")
//    public ModelAndView deleteCommentByAuthor(@RequestParam int commentId, HttpServletRequest request) {
//        try {
//            int userId = (int) request.getSession().getAttribute("userId");
//            String result = videosService.deleteCommentByAuthor(commentId, userId);
//
//            if ("无权删除该评论".equals(result)) {
//                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, result);
//            }
//            if ("评论不存在".equals(result)) {
//                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, result);
//            }
//
//            ModelAndView mav = new ModelAndView();
//            mav.addObject("result", result);
//            return mav;
//        } catch (BusinessException e) {
//            throw e;
//        } catch (Exception e) {
//            throw new SystemException(Code.SYSTEM_DB_ERROR, "删除评论时数据库错误", e);
//        }
//    }
}

